<template>
  <div class="student-management">
    <!-- 页面标题和班级选择 -->
    <div class="page-header">
      <h1>学生管理</h1>
      <el-select 
        v-model="selectedClassId" 
        placeholder="请选择班级"
        class="class-select"
        @change="handleClassChange"
        :disabled="loading"
      >
        <el-option 
          v-for="cls in sortedTeacherClasses" 
          :key="cls.id" 
          :value="cls.id"
          :label="`${cls.grade}年级${cls.name}`"
        />
      </el-select>
    </div>

    <!-- 学生和小组卡片容器 -->
    <div class="card-container">
      <!-- 学生列表卡片 -->
      <el-card class="content-card">
        <div class="card-header">
          <h2>学生列表</h2>
          <el-button 
            type="primary" 
            size="small" 
            @click="openCreateStudentDialog"
            :disabled="!selectedClassId"
          >
            <el-icon><Plus /></el-icon>
            创建学生账号
          </el-button>
        </div>

        <el-table 
          :data="studentList" 
          border 
          stripe
          :loading="studentLoading"
          v-if="selectedClassId"
        >
          <el-table-column prop="student_number" label="学号" width="80" align="center"/>
          <el-table-column prop="student_name" label="学生姓名" width="100" />
          <el-table-column prop="performance_points" label="积分" width="80" />
          <el-table-column prop="rank" label="排名" width="80" />
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button 
                type="text" 
                size="small" 
                @click="openEditStudentDialog(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="openStudentDetailDialog(scope.row.student_id)"
              >
                详情
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="openPointOperationDialog(scope.row)"
                color="#409eff">
                积分操作
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="empty-hint">请选择班级查看学生列表</div>
      </el-card>

      <!-- 小组列表卡片 -->
      <el-card class="content-card">
        <div class="card-header">
          <h2>小组列表</h2>
          <el-button 
            type="primary" 
            size="small" 
            @click="openCreateGroupDialog"
            :disabled="!selectedClassId"
          >
            <el-icon><Plus /></el-icon>
            创建小组
          </el-button>
        </div>

        <el-table 
          :data="groupList" 
          border 
          stripe
          :loading="groupLoading"
          v-if="selectedClassId"
        >
          <el-table-column prop="group_name" label="小组名称" width="150" />
          <el-table-column prop="total_points" label="积分" width="80" />
          <el-table-column prop="rank" label="排名" width="50" />
          <el-table-column prop="leader_info.leader_name" label="组长姓名" width="80" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button 
                type="text" 
                size="small" 
                @click="openEditGroupDialog(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                @click="openGroupMembersDialog(scope.row.group_id)"
              >
                编辑成员
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="empty-hint">请选择班级查看小组列表</div>
      </el-card>
    </div>

    <!-- 创建学生对话框 -->
    <el-dialog 
      v-model="createStudentDialogVisible" 
      title="创建学生账号" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="createStudentForm" 
        :rules="createStudentRules" 
        ref="createStudentFormRef" 
        label-width="120px"
      >
        <el-form-item label="选择班级" prop="classId">
          <el-select 
            v-model="createStudentForm.classId" 
            placeholder="请选择班级"
          >
            <el-option 
              v-for="cls in sortedTeacherClasses" 
              :key="cls.id" 
              :value="cls.id"
              :label="`${cls.grade}年级${cls.name}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学生学号" prop="studentId">
          <el-input v-model="createStudentForm.studentId" placeholder="请输入学生学号" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="createStudentForm.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="教师口令" prop="teacherPassword">
          <el-input 
            v-model="createStudentForm.teacherPassword" 
            type="password" 
            placeholder="请输入教师口令"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createStudentDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreateStudent"
          :loading="createStudentLoading"
        >
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑学生对话框 -->
    <el-dialog 
      v-model="editStudentDialogVisible" 
      title="编辑学生信息" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editStudentForm" 
        :rules="editStudentRules" 
        ref="editStudentFormRef" 
        label-width="120px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="editStudentForm.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="editStudentForm.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="所属班级" prop="classId">
          <el-select 
            v-model="editStudentForm.classId" 
            placeholder="请选择班级"
          >
            <el-option 
              v-for="cls in sortedTeacherClasses" 
              :key="cls.id" 
              :value="cls.id"
              :label="`${cls.grade}年级${cls.name}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input 
            v-model="editStudentForm.password" 
            type="password" 
            placeholder="不修改请留空"
          />
        </el-form-item>
        <el-form-item label="重复密码" prop="confirmPassword">
          <el-input 
            v-model="editStudentForm.confirmPassword" 
            type="password" 
            placeholder="不修改请留空"
          />
        </el-form-item>
        <el-form-item label="教师口令" prop="teacherPassword">
          <el-input 
            v-model="editStudentForm.teacherPassword" 
            type="password" 
            placeholder="请输入教师口令"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editStudentDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleUpdateStudent"
          :loading="editStudentLoading"
        >
          修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 学生详情对话框（优化版） -->
    <el-dialog 
        v-model="studentDetailDialogVisible" 
        title="学生详情" 
        :close-on-click-modal="false"
        width="550px"
    >
        <div class="student-detail-container" v-if="studentDetail">
        <!-- 顶部信息栏（班级+学号） -->
        <div class="detail-header">
            <div class="detail-header-item">
            <el-icon class="detail-icon"><School /></el-icon>
            <div class="detail-label">所在班级</div>
            <div class="detail-value">{{ `${studentDetail.grade}年级${studentDetail.class_name}` }}</div>
            </div>
            <div class="detail-header-item">
            <el-icon class="detail-icon"><Memo /></el-icon>
            <div class="detail-label">学生学号</div>
            <div class="detail-value">{{ studentDetail.student_id }}</div>
            </div>
        </div>

        <!-- 中间核心信息（姓名+积分） -->
        <div class="detail-core">
            <div class="core-item">
            <el-icon class="core-icon"><User /></el-icon>
            <div class="core-label">登录账号</div>
            <div class="core-value">{{ studentDetail.username }}</div>
            </div>
            <div class="core-item">
            <el-icon class="core-icon"><UserFilled /></el-icon>
            <div class="core-label">学生姓名</div>
            <div class="core-value">{{ studentDetail.student_name }}</div>
            </div>
            <div class="core-item">
            <el-icon class="core-icon"><Coin /></el-icon>
            <div class="core-label">行规积分</div>
            <div class="core-value highlight">{{ studentDetail.performance_points }}</div>
            </div>
        </div>

        <!-- 底部双列信息（排名+小组） -->
        <div class="detail-footer">
            <div class="footer-item">
            <el-icon class="footer-icon"><Histogram /></el-icon>
            <div class="footer-label">积分班级排名</div>
            <div class="footer-value">{{ studentDetail.class_rank }}</div>
            </div>
            <div class="footer-item">
            <el-icon class="footer-icon"><Flag /></el-icon>
            <div class="footer-label">所属小组</div>
            <div class="footer-value">{{ studentDetail.group_name || '未分组' }}</div>
            </div>
            <div class="footer-item">
            <el-icon class="footer-icon"><Coin /></el-icon>
            <div class="footer-label">小组积分</div>
            <div class="footer-value">{{ studentDetail.group_total_points || '0' }}</div>
            </div>
            <div class="footer-item">
            <el-icon class="footer-icon"><Histogram /></el-icon>
            <div class="footer-label">小组排名</div>
            <div class="footer-value">{{ studentDetail.group_rank || '无' }}</div>
            </div>
        </div>
        </div>
        <el-skeleton :count="6" v-else />
        <template #footer>
        <el-button @click="studentDetailDialogVisible = false">关闭</el-button>
        </template>
    </el-dialog>

    <!-- 创建小组对话框 -->
    <el-dialog 
      v-model="createGroupDialogVisible" 
      title="创建小组" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="createGroupForm" 
        :rules="createGroupRules" 
        ref="createGroupFormRef" 
        label-width="120px"
      >
        <el-form-item label="小组名称" prop="groupName">
          <el-input v-model="createGroupForm.groupName" placeholder="请输入小组名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createGroupDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreateGroup"
          :loading="createGroupLoading"
        >
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑小组对话框 -->
    <el-dialog 
      v-model="editGroupDialogVisible" 
      title="编辑小组" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editGroupForm" 
        :rules="editGroupRules" 
        ref="editGroupFormRef" 
        label-width="120px"
      >
        <el-form-item label="小组名称" prop="groupName">
          <el-input v-model="editGroupForm.groupName" placeholder="请输入小组名称" />
        </el-form-item>
        <el-form-item label="所属班级" prop="classId">
          <el-select 
            v-model="editGroupForm.classId" 
            placeholder="请选择班级"
          >
            <el-option 
              v-for="cls in sortedTeacherClasses" 
              :key="cls.id" 
              :value="cls.id"
              :label="`${cls.grade}年级${cls.name}`"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editGroupDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleUpdateGroup"
          :loading="editGroupLoading"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 小组成员对话框 -->
    <el-dialog 
      v-model="groupMembersDialogVisible" 
      title="编辑小组成员" 
      :close-on-click-modal="false"
      width="700px"
    >
      <div class="member-header">
        <el-button 
          type="primary" 
          size="small" 
          @click="openAddMembersDialog"
        >
          <el-icon><Plus /></el-icon>
          新增成员
        </el-button>
      </div>
      <el-table 
        :data="groupMembers" 
        border 
        :loading="groupMembersLoading"
      >
        <el-table-column prop="student_number" label="学号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column label="身份">
          <template #default="scope">
            <el-tag v-if="scope.row.is_leader" type="success">组长</el-tag>
            <span v-else>成员</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="handleSetLeader(scope.row.student_id)"
              :disabled="scope.row.is_leader"
            >
              设为组长
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              text-color="#ff4d4f"
              @click="handleRemoveMember(scope.row.student_id)"
              :disabled="scope.row.is_leader"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="groupMembersDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加成员对话框 -->
    <el-dialog 
      v-model="addMembersDialogVisible" 
      title="添加小组成员" 
      :close-on-click-modal="false"
      width="600px"
    >
      <el-input 
        v-model="noGroupStudentFilter" 
        placeholder="输入学生姓名搜索" 
        prefix-icon="Search"
        class="member-search"
        @input="handleNoGroupStudentSearch"
      />
      <el-table 
        :data="noGroupStudents" 
        border 
        :loading="noGroupStudentsLoading"
        ref="memberTableRef"
        row-key="student_id"
        style="margin-top: 10px;"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="student_number" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" />
      </el-table>
      <template #footer>
        <el-button @click="addMembersDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleAddMembers"
          :loading="addMembersLoading"
        >
          加入小组
        </el-button>
      </template>
    </el-dialog>

    <!-- 积分操作对话框 -->
    <el-dialog 
        v-model="pointOperationDialogVisible" 
        title="积分操作" 
        :close-on-click-modal="false"
    >
        <el-form 
        :model="pointOperationForm" 
        :rules="pointOperationRules" 
        ref="pointOperationFormRef" 
        label-width="120px"
        >
        <el-form-item label="积分变化" prop="points">
            <el-input-number 
            v-model="pointOperationForm.points" 
            :min="-100"
            :max="100" 
            :step="1" 
            placeholder="请输入积分变化值"
            controls-position="right"
            />
            <div class="form-hint">正数为加分，负数为扣分</div>
        </el-form-item>
        <el-form-item label="操作理由" prop="reasonType">
            <el-select 
            v-model="pointOperationForm.reasonType" 
            placeholder="请选择理由类型"
            @change="handleReasonTypeChange"
            >
            <el-option 
                v-for="reason in pointReasons" 
                :key="reason" 
                :value="reason"
            />
            <el-option value="other" label="其他" />
            </el-select>
        </el-form-item>
        <el-form-item 
            label="自定义理由" 
            prop="customReason"
            v-if="pointOperationForm.reasonType === 'other'"
        >
            <el-input 
            v-model="pointOperationForm.customReason" 
            placeholder="请输入自定义理由"
            type="textarea"
            rows="3"
            />
        </el-form-item>
        <el-form-item label="教师口令" prop="teacherPassword">
            <el-input 
            v-model="pointOperationForm.teacherPassword" 
            type="password" 
            placeholder="请输入教师口令"
            />
        </el-form-item>
        </el-form>
        <template #footer>
        <el-button @click="pointOperationDialogVisible = false">取消</el-button>
        <el-button 
            type="primary" 
            @click="handleUpdatePoint"
            :loading="pointOperationLoading"
        >
            确定
        </el-button>
        </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { ElMessage, ElTable } from 'element-plus';
import type { ElForm } from 'element-plus';
import { getStudentInfoById } from '../../api/user';
import { listClasses } from '../../api/classmgr';
import type { ClassItem } from '../../api/classmgr';
import { 
  getStudentRanking,
  createStudent,
  updateStudent,
  listNoGroupStudents,
  type StudentRankingItem,
  type NoGroupStudentItem
} from '../../api/studentmgr';
import { 
  getGroupRanking,
  createGroup,
  updateGroup,
  getGroupMembers,
  removeGroupStudent,
  setGroupLeader,
  addGroupStudents,
  type GroupRankingItem,
  type GroupMemberItem
} from '../../api/group';
import type { StudentInfoResponse } from '../../api/user';
import { Plus, School, Memo, UserFilled, Coin, Flag, Histogram } from '@element-plus/icons-vue';
import { getPointReasons, updatePoint } from '../../api/point';

// 班级相关
const allClasses = ref<ClassItem[]>([]);
const selectedClassId = ref<number | undefined>(undefined);
const loading = ref(true);

// 班级排序处理（新增）
const sortedTeacherClasses = computed(() => {
  // 先按年级升序，再按班级名称升序排序
  return [...allClasses.value].sort((a, b) => {
    if (a.grade !== b.grade) {
      return a.grade - b.grade;
    }
    // 假设班级名称是数字字符串，如"1班"、"2班"，提取数字进行比较
    const classA = parseInt(a.name);
    const classB = parseInt(b.name);
    return classA - classB;
  });
});

// 学生列表相关
const studentList = ref<StudentRankingItem[]>([]);
const studentLoading = ref(false);

// 小组列表相关
const groupList = ref<GroupRankingItem[]>([]);
const groupLoading = ref(false);

// 积分操作相关状态
const pointOperationDialogVisible = ref(false);
const pointOperationLoading = ref(false);
const pointOperationFormRef = ref<InstanceType<typeof ElForm>>();
const pointReasons = ref<string[]>([]); // 预设理由列表
const currentStudent = ref<StudentRankingItem | null>(null);
const pointOperationForm = reactive({
  points: 0,
  reasonType: '', // 预设理由或'other'
  customReason: '', // 自定义理由
  teacherPassword: ''
});
const pointOperationRules = {
  points: [
    { required: true, message: '请输入积分变化值', trigger: 'blur' },
    { 
      validator: (_: any, value: number, callback: any) => {
        if (value === 0) {
          callback(new Error('积分变化值不能为0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  reasonType: [{ required: true, message: '请选择理由类型', trigger: 'change' }],
  customReason: [
    { 
      required: true, 
      message: '请输入自定义理由', 
      trigger: 'blur',
      when: () => pointOperationForm.reasonType === 'other'
    }
  ],
  teacherPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }]
};

// 页面加载时获取数据
onMounted(async () => {
  try {
    loading.value = true;
    
    // 获取所有未毕业班级（用于编辑学生的班级选择）
    const classesRes = await listClasses();
    if (classesRes.code === 200) {
      allClasses.value = classesRes.content;
      // 默认选择第一个班级
      if (sortedTeacherClasses.value.length > 0) {
        selectedClassId.value = sortedTeacherClasses.value[0]?.id ?? NaN;
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '初始化数据失败');
  } finally {
    loading.value = false;
  }

  // 页面加载时获取积分操作理由
  try {
    const res = await getPointReasons();
    if (res.code === 200) {
      pointReasons.value = res.content.reasons.map(item => item.reason);
    } else {
      ElMessage.error(res.msg || '获取积分操作理由失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取积分操作理由异常');
  }
});

// 监听班级变化，加载对应数据
watch(selectedClassId, (newVal) => {
  if (newVal) {
    fetchStudentList();
    fetchGroupList();
  } else {
    studentList.value = [];
    groupList.value = [];
  }
});

// 获取学生列表
const fetchStudentList = async () => {
  try {
    studentLoading.value = true;
    const res = await getStudentRanking({ class_id: selectedClassId.value ?? 0 });
    if (res.code === 200 || res.code === 404) {
      studentList.value = res.content.ranking_list;
    } else {
      ElMessage.error(res.msg || '获取学生列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取学生列表异常');
  } finally {
    studentLoading.value = false;
  }
};

// 获取小组列表
const fetchGroupList = async () => {
  try {
    groupLoading.value = true;
    const res = await getGroupRanking({ class_id: selectedClassId.value ?? 0 });
    if (res.code === 200 || res.code === 404) {
      groupList.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取小组列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取小组列表异常');
  } finally {
    groupLoading.value = false;
  }
};

// 班级选择变化处理
const handleClassChange = (val: number) => {
  selectedClassId.value = val;
};

// 创建学生相关
const createStudentDialogVisible = ref(false);
const createStudentLoading = ref(false);
const createStudentFormRef = ref<InstanceType<typeof ElForm>>();
const createStudentForm = reactive({
  classId: 0,
  studentId: '',
  name: '',
  teacherPassword: ''
});
const createStudentRules = {
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  studentId: [{ required: true, message: '请输入学生学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
  teacherPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }]
};

// 打开创建学生对话框
const openCreateStudentDialog = () => {
  createStudentForm.classId = selectedClassId.value ?? 0;
  createStudentForm.studentId = '';
  createStudentForm.name = '';
  createStudentForm.teacherPassword = '';
  createStudentDialogVisible.value = true;
};

// 处理创建学生
const handleCreateStudent = async () => {
  if (!createStudentFormRef.value) return;
  
  try {
    createStudentLoading.value = true;
    await createStudentFormRef.value.validate();
    
    const res = await createStudent({
      class_id: createStudentForm.classId,
      student_id: createStudentForm.studentId,
      name: createStudentForm.name,
      teacher_password: createStudentForm.teacherPassword
    });
    
    if (res.code === 200) {
      createStudentDialogVisible.value = false;
      fetchStudentList();
      ElMessage.success('学生账号创建成功');
    } else {
      ElMessage.error(res.msg || '创建学生账号失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '创建学生账号异常');
  } finally {
    createStudentLoading.value = false;
  }
};

// 编辑学生相关
const editStudentDialogVisible = ref(false);
const editStudentLoading = ref(false);
const editStudentFormRef = ref<InstanceType<typeof ElForm>>();
const editStudentForm = reactive({
  userId: 0,
  studentId: '',
  name: '',
  classId: 0,
  password: '',
  confirmPassword: '',
  teacherPassword: ''
});
const editStudentRules = {
  studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  password: [
    { 
      validator: (_: any, value: string, callback: any) => {
        if (value && value.length < 6) {
          callback(new Error('密码长度不能少于6位'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { 
      validator: (_: any, value: string, callback: any) => {
        if (value && value !== editStudentForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  teacherPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }]
};

// 打开编辑学生对话框时记录原始值
const originalStudentData = ref<{
  studentId: string;
  name: string;
  classId: number;
}>({
  studentId: '',
  name: '',
  classId: 0
});

// 打开编辑学生对话框
const openEditStudentDialog = (student: StudentRankingItem) => {
  // 记录原始值用于对比
  originalStudentData.value = {
    studentId: student.student_number,
    name: student.student_name,
    classId: student.class_id
  };
  
  // 初始化表单
  editStudentForm.userId = student.user_id;
  editStudentForm.studentId = student.student_number;
  editStudentForm.name = student.student_name;
  editStudentForm.classId = selectedClassId.value ?? 0; // 全局班级
  editStudentForm.password = '';
  editStudentForm.confirmPassword = '';
  editStudentForm.teacherPassword = '';
  editStudentDialogVisible.value = true;
};

// 处理更新学生
const handleUpdateStudent = async () => {
  if (!editStudentFormRef.value) return;
  
  try {
    editStudentLoading.value = true;
    await editStudentFormRef.value.validate();
    
    // 构建参数对象（只包含有改动的字段）
    const updateParams: any = {
      user_id: editStudentForm.userId,
      admin_password: editStudentForm.teacherPassword
    };
    
    // 对比原始值，只有改动过的字段才加入参数
    if (editStudentForm.studentId !== originalStudentData.value.studentId) {
      updateParams.student_id = editStudentForm.studentId;
    }
    if (editStudentForm.name !== originalStudentData.value.name) {
      updateParams.name = editStudentForm.name;
    }
    if (editStudentForm.classId !== originalStudentData.value.classId) {
      updateParams.class_id = editStudentForm.classId;
    }
    // 密码字段如果填写了才传递
    if (editStudentForm.password) {
      updateParams.password = editStudentForm.password;
      updateParams.confirm_password = editStudentForm.confirmPassword;
    }
    
    // 调用接口
    const res = await updateStudent(updateParams);
    
    if (res.code === 200) {
      editStudentDialogVisible.value = false;
      fetchStudentList();
      ElMessage.success('学生信息更新成功');
    } else {
      ElMessage.error(res.msg || '更新学生信息失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '更新学生信息异常');
  } finally {
    editStudentLoading.value = false;
  }
};

// 学生详情相关
const studentDetailDialogVisible = ref(false);
const studentDetail = ref<StudentInfoResponse['content'] | null>(null);

// 打开学生详情对话框
const openStudentDetailDialog = async (studentId: number) => {
  try {
    studentDetailDialogVisible.value = true;
    studentDetail.value = null;
    const res = await getStudentInfoById(studentId); // 注意：需要在api/user.ts中补充带参数的getStudentInfo
    if (res.code === 200) {
      studentDetail.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取学生详情失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取学生详情异常');
  }
};

// 创建小组相关
const createGroupDialogVisible = ref(false);
const createGroupLoading = ref(false);
const createGroupFormRef = ref<InstanceType<typeof ElForm>>();
const createGroupForm = reactive({
  groupName: '',
  teacherPassword: ''
});
const createGroupRules = {
  groupName: [{ required: true, message: '请输入小组名称', trigger: 'blur' }],
  teacherPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }]
};

// 打开创建小组对话框
const openCreateGroupDialog = () => {
  createGroupForm.groupName = '';
  createGroupForm.teacherPassword = '';
  createGroupDialogVisible.value = true;
};

// 处理创建小组
const handleCreateGroup = async () => {
  if (!createGroupFormRef.value) return;
  
  try {
    createGroupLoading.value = true;
    await createGroupFormRef.value.validate();
    
    const res = await createGroup({
      name: createGroupForm.groupName,
      class_id: selectedClassId.value ?? 0
    });
    
    if (res.code === 200) {
      createGroupDialogVisible.value = false;
      fetchGroupList();
      ElMessage.success('小组创建成功');
    } else {
      ElMessage.error(res.msg || '创建小组失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '创建小组异常');
  } finally {
    createGroupLoading.value = false;
  }
};

// 编辑小组相关
const editGroupDialogVisible = ref(false);
const editGroupLoading = ref(false);
const editGroupFormRef = ref<InstanceType<typeof ElForm>>();
const editGroupForm = reactive({
  groupId: 0,
  groupName: '',
  classId: 0,
  teacherPassword: ''
});
const editGroupRules = {
  groupName: [{ required: true, message: '请输入小组名称', trigger: 'blur' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  teacherPassword: [{ required: true, message: '请输入教师口令', trigger: 'blur' }]
};

// 打开编辑小组对话框
const openEditGroupDialog = (group: GroupRankingItem) => {
  editGroupForm.groupId = group.group_id;
  editGroupForm.groupName = group.group_name;
  editGroupForm.classId = selectedClassId.value ?? 0;
  editGroupForm.teacherPassword = '';
  editGroupDialogVisible.value = true;
};

// 处理更新小组
const handleUpdateGroup = async () => {
  if (!editGroupFormRef.value) return;
  
  try {
    editGroupLoading.value = true;
    await editGroupFormRef.value.validate();
    
    const res = await updateGroup({
      group_id: editGroupForm.groupId,
      name: editGroupForm.groupName,
      class_id: editGroupForm.classId
    });
    
    if (res.code === 200) {
      editGroupDialogVisible.value = false;
      fetchGroupList();
      ElMessage.success('小组信息更新成功');
    } else {
      ElMessage.error(res.msg || '更新小组信息失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '更新小组信息异常');
  } finally {
    editGroupLoading.value = false;
  }
};

// 小组成员相关
const groupMembersDialogVisible = ref(false);
const currentGroupId = ref(0);
const groupMembers = ref<GroupMemberItem[]>([]);
const groupMembersLoading = ref(false);

// 打开小组成员对话框
const openGroupMembersDialog = async (groupId: number) => {
  try {
    currentGroupId.value = groupId;
    groupMembersDialogVisible.value = true;
    groupMembersLoading.value = true;
    const res = await getGroupMembers({ group_id: groupId });
    if (res.code === 200) {
      groupMembers.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取小组成员失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取小组成员异常');
  } finally {
    groupMembersLoading.value = false;
  }
};

// 设为组长
const handleSetLeader = async (studentId: number) => {
  try {
    const res = await setGroupLeader({
      group_id: currentGroupId.value,
      leader_id: studentId
    });
    
    if (res.code === 200) {
      ElMessage.success('设置组长成功');
      // 刷新成员列表
      const membersRes = await getGroupMembers({ group_id: currentGroupId.value });
      if (membersRes.code === 200) {
        groupMembers.value = membersRes.content;
      }
      // 刷新小组列表，更新组长信息
      fetchGroupList();
    } else {
      ElMessage.error(res.msg || '设置组长失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '设置组长异常');
  }
};

// 移除成员
const handleRemoveMember = async (studentId: number) => {
  try {
    const res = await removeGroupStudent({
      group_id: currentGroupId.value,
      student_id: studentId
    });
    
    if (res.code === 200) {
      ElMessage.success('移除成员成功');
      // 刷新成员列表
      const membersRes = await getGroupMembers({ group_id: currentGroupId.value });
      if (membersRes.code === 200) {
        groupMembers.value = membersRes.content;
      }
      // 刷新小组列表，更新排名信息
      fetchGroupList();
    } else {
      ElMessage.error(res.msg || '移除成员失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '移除成员异常');
  }
};

// 添加成员相关
const addMembersDialogVisible = ref(false);
const noGroupStudentFilter = ref('');
const noGroupStudents = ref<NoGroupStudentItem[]>([]);
const noGroupStudentsLoading = ref(false);
const addMembersLoading = ref(false);
const memberTableRef = ref<InstanceType<typeof ElTable>>();

// 打开添加成员对话框
const openAddMembersDialog = async () => {
  addMembersDialogVisible.value = true;
  noGroupStudentFilter.value = '';
  await fetchNoGroupStudents();
};

// 获取无小组学生
const fetchNoGroupStudents = async () => {
  try {
    noGroupStudentsLoading.value = true;
    const res = await listNoGroupStudents({
      class_id: selectedClassId.value ?? 0,
      has_group: 0,
      name: noGroupStudentFilter.value || undefined
    });
    
    if (res.code === 200) {
      noGroupStudents.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取学生列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取学生列表异常');
  } finally {
    noGroupStudentsLoading.value = false;
  }
};

// 搜索无小组学生
const handleNoGroupStudentSearch = (_: string) => {
  // 防抖处理
  const timer = setTimeout(() => {
    fetchNoGroupStudents();
    clearTimeout(timer);
  }, 300);
};

// 处理添加成员
const handleAddMembers = async () => {
  if (!memberTableRef.value) return;
  
  const selectedRows = memberTableRef.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要添加的学生');
    return;
  }
  
  try {
    addMembersLoading.value = true;
    const studentIds = selectedRows.map(row => row.student_id);
    
    const res = await addGroupStudents({
      group_id: currentGroupId.value,
      student_ids: studentIds
    });
    
    if (res.code === 200) {
      addMembersDialogVisible.value = false;
      ElMessage.success('添加成员成功');
      // 刷新成员列表
      const membersRes = await getGroupMembers({ group_id: currentGroupId.value });
      if (membersRes.code === 200) {
        groupMembers.value = membersRes.content;
      }
      // 刷新小组列表，更新排名信息
      fetchGroupList();
    } else {
      ElMessage.error(res.msg || '添加成员失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '添加成员异常');
  } finally {
    addMembersLoading.value = false;
  }
};

// 打开积分操作对话框
const openPointOperationDialog = (student: StudentRankingItem) => {
  currentStudent.value = student;
  pointOperationForm.points = 0;
  pointOperationForm.reasonType = '';
  pointOperationForm.customReason = '';
  pointOperationForm.teacherPassword = '';
  pointOperationDialogVisible.value = true;
};

// 理由类型变化处理
const handleReasonTypeChange = (value: string) => {
  if (value !== 'other') {
    pointOperationForm.customReason = '';
  }
};

// 处理积分更新
const handleUpdatePoint = async () => {
  if (!pointOperationFormRef.value || !currentStudent.value) return;
  
  try {
    pointOperationLoading.value = true;
    await pointOperationFormRef.value.validate();

    // 确定最终理由
    const reason = pointOperationForm.reasonType === 'other' 
      ? pointOperationForm.customReason 
      : pointOperationForm.reasonType;
    
    const res = await updatePoint({
      student_id: currentStudent.value.student_id,
      points_change: pointOperationForm.points,
      reason,
      admin_password: pointOperationForm.teacherPassword
    });
    
    if (res.code === 200) {
      pointOperationDialogVisible.value = false;
      // 刷新学生列表和小组列表（积分变化会影响排名）
      fetchStudentList();
      fetchGroupList();
      ElMessage.success('积分操作成功');
    } else {
      ElMessage.error(res.msg || '积分操作失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '积分操作异常');
  } finally {
    pointOperationLoading.value = false;
  }
};
</script>

<style scoped>
.student-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.class-select {
  width: 220px;
}

.card-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  
}

.content-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.empty-hint {
  text-align: center;
  padding: 50px 0;
  color: var(--el-text-color-secondary);
}

.student-detail {
  padding: 10px 0;
}

.detail-item {
  margin-bottom: 15px;
  font-size: 14px;
}

.detail-label {
  display: inline-block;
  width: 100px;
  color: var(--el-text-color-secondary);
}

.detail-value {
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.member-header {
  margin-bottom: 15px;
  text-align: right;
}

.member-search {
  width: 100%;
}

.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .card-container {
    grid-template-columns: 1fr;
  }
}

/* 优化后的详情样式 */
.student-detail-container {
  padding: 15px 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 顶部信息栏 */
.detail-header {
  display: flex;
  gap: 20px;
  padding: 15px;
  background-color: #f5fafe;
  border-radius: 8px;
}

.detail-header-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 中间核心信息 */
.detail-core {
  display: flex;
  gap: 20px;
  padding: 20px 15px;
  background-color: #f0f9ff;
  border-radius: 8px;
}

.core-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 底部双列信息 */
.detail-footer {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.footer-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

/* 图标样式统一 */
.detail-icon, .core-icon, .footer-icon {
  color: #409eff;
  font-size: 20px;
  width: 24px;
  text-align: center;
}

.core-icon {
  font-size: 24px;
  margin-bottom: 5px;
  align-self: center;
}

/* 文字样式层级 */
.detail-label, .core-label, .footer-label {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  margin-bottom: 2px;
}

.detail-value, .footer-value {
  color: var(--el-text-color-primary);
  font-size: 15px;
  font-weight: 500;
}

.core-label {
  font-size: 14px;
  text-align: center;
}

.core-value {
  font-size: 22px;
  font-weight: 600;
  text-align: center;
}

/* 高亮积分样式 */
.highlight {
  color: #409eff;
  font-size: 26px;
  font-weight: 700;
}

.warning-text {
  color: #f56c6c;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fef0f0;
  border-radius: 4px;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .detail-header, .detail-core {
    flex-direction: column;
    gap: 15px;
  }
  
  .detail-footer {
    grid-template-columns: 1fr;
  }
}
</style>